package a_doubleWrite;

import util.ListNode;

/**
 23. 合并K个升序链表
 给你一个链表数组，每个链表都已经按升序排列。
 请你将所有链表合并到一个升序链表中，返回合并后的链表。
 * @author: luolidong
 * @create: 2021-07-17 10:16
 * @version: 1.0
 */
public class L23 {
    public ListNode mergeKLists(ListNode[] lists) {
        //1.判空
        if(lists.length==0) return null;
        if(lists.length==1) return lists[0];
        //2.分治思想
        return mergeList(lists, 0, lists.length-1);
    }
    public ListNode mergeList(ListNode[] lists,int left,int right){
        if(left==right) return lists[left];
        int mid=(left+right)/2;
        ListNode l1 = mergeList(lists, left, mid);
        ListNode l2 = mergeList(lists, mid + 1, right);
        return merge(l1,l2);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode dummy=new ListNode(0);
        ListNode cur=dummy;
        while (l1!=null&&l2!=null){
            if(l1.val<l2.val){
                cur.next=l1;
                l1=l1.next;
            }else {
                cur.next=l2;
                l2=l2.next;
            }
            cur=cur.next;
        }
        cur.next=l1==null? l2:l1;
        return dummy.next;
    }
}
